package com.haiyou.common.security;

import org.springframework.util.StringUtils;

import com.haiyou.common.constants.ErrorCode;
import com.haiyou.common.system.Properties;
import com.haiyou.common.util.file.FileUtils;
import com.haiyou.common.util.check.Assert;
import com.haiyou.common.util.encryption.*;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @Description: 服务器通信加密解密器,签名工具
 * @author xingyuan
 * @date 2022年11月24日 上午11:12:39
 */
@Slf4j
public class RSASecurityService {
	
	/**
	 * 解密器
	 */
	private com.haiyou.common.util.encryption.RSADecrypt RSADecrypt;
	
	/**
	 * 加密器
	 */
	private RSAEncrypt RSAEncrypt;
	
	/**
	 * 签名器
	 */
	private RSASign RSASign;
	
	/**
	 * 签名验证器
	 */
	private RSASignVerify RSASignVerify;
	
	private static final class Lazy {
		private static final RSASecurityService instance;
		static {
			instance = new RSASecurityService();
		}
	}
	
	public static RSASecurityService instance() {
		return Lazy.instance;
	}
	
	private RSASecurityService() {
		
		log.info("=========RSASecurityService 执行初始化=========");
		
		//私钥地址
		String privateKeyPath = Properties.server_private_key_path();
		//公钥地址
		String publicKeyPath = Properties.server_public_key_path();

		//私钥
		String privateKey = "";
		//公钥
		String publicKey = "";
		
		try {
			privateKey = FileUtils.readFileToString(privateKeyPath);
		}catch (Exception e) {
			log.info(e.getMessage(),e);
		}
		
		try {
			publicKey = FileUtils.readFileToString(publicKeyPath);
		}catch (Exception e) {
			log.info(e.getMessage(),e);
		}
		
		if(StringUtils.hasLength(privateKey)) {
			//成功读取到私钥
			this.RSADecrypt = new RSADecrypt(privateKey);
			this.RSASign = new RSASign(privateKey);
			log.info("===成功读取到私钥 初始化成功==");
		}
		
		if(StringUtils.hasLength(publicKey)) {
			this.RSASignVerify = new RSASignVerify(publicKey);
			this.RSAEncrypt = new RSAEncrypt(publicKey);
			log.info("===成功读取到公钥 初始化成功==");
		}
	}

	/**
	 * 解密器
	 * @return
	 */
	public RSADecrypt RSADecrypt() {
		Assert.isTrue(RSADecrypt !=null , ErrorCode.SDK_PAY_SYSTEM_ERROR,"RSADecrypt not init");
		return RSADecrypt;
	}
	/**
	 * 加密器
	 * @return
	 */
	public RSAEncrypt RSAEncrypt() {
		Assert.isTrue(RSAEncrypt !=null , ErrorCode.SDK_PAY_SYSTEM_ERROR,"RSAEncrypt not init");
		return RSAEncrypt;
	}
	/**
	 * 签名器
	 * @return
	 */
	public RSASign RSASign() {
		Assert.isTrue(RSASign !=null , ErrorCode.SDK_PAY_SYSTEM_ERROR,"RSASign not init");
		return RSASign;
	}
	/**
	 * 签名验证器
	 * @return
	 */
	public RSASignVerify RSASignVerify() {
		Assert.isTrue(RSASignVerify !=null , ErrorCode.SDK_PAY_SYSTEM_ERROR,"RSASignVerify not init");
		return RSASignVerify;
	}


}
